package com.example.administrator.runbook.findfragment.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.runbook.R;
import com.example.administrator.runbook.findfragment.adapter.MyListAdapter;
import com.example.administrator.runbook.findfragment.model.BookMessage;
import com.example.administrator.runbook.findfragment.model.BookMessageList;
import com.example.administrator.runbook.findfragment.model.FileCache;
import com.example.administrator.runbook.findfragment.network.GetFindClassifyService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 俊峰 on 2016/11/11.
 */

public class BookMyActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private String view;
    private List<BookMessageList.MessageList> chapters;
    private String mMessage;
    private MyListAdapter mAdapter;
    private GetFindClassifyService mGetFindClassifyService;
    private RelativeLayout mAnimAll;
    private ImageView mWaitAnim;
    private Drawable mDrawable;
    private ProgressDialog mProgressDialog;
    private GetFindClassifyService mGetFindClassifyServiceSecond;
    private BookMessage.BookChapter mBookChapters;
    private List<Integer> myIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list_dialog);
        view = "chapters";
        chapters = new ArrayList<>();
        myIndex = new ArrayList<>();
        mMessage = getIntent().getStringExtra("MyBookMessage");
        ListView listView = (ListView) findViewById(R.id.activity_book_list_item_message);
        mAnimAll = (RelativeLayout) findViewById(R.id.activity_find_classify_wait);
        mWaitAnim = (ImageView) findViewById(R.id.activity_find_classify_wait_img);
        startAnim();
        mAdapter = new MyListAdapter(this, chapters);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(this);
        initNetWork();
        getData();
    }

    @Override
    public void setToolBarTitleText(TextView toolBarTitleText) {
        if (toolBarTitleText != null) {
            toolBarTitleText.setText("小说目录");
        }
    }

    @Override
    public void setBackImg(ImageView backImg) {
        if (backImg != null) {
            backImg.setOnClickListener(this);
        }
    }

    private void initNetWork() {
        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit.Builder myBuilder = builder.baseUrl("http://api.zhuishushenqi.com");
        myBuilder.addConverterFactory(ScalarsConverterFactory.create());
        myBuilder.addConverterFactory(GsonConverterFactory.create());
        myBuilder.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.newThread()));
        Retrofit build = myBuilder.build();
        mGetFindClassifyService = build.create(GetFindClassifyService.class);
    }

    public void getData() {
        Observable<BookMessageList> bookMessageList = mGetFindClassifyService.getBookMessageList(mMessage, view);
        bookMessageList.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BookMessageList>() {
                    @Override
                    public void onCompleted() {
                        mAdapter.notifyDataSetChanged();
                        stopAnim();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(BookMyActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BookMessageList list) {
                        chapters.addAll(list.getChapters());
                    }
                });
    }

    private void startAnim() {
        mDrawable = mWaitAnim.getDrawable();
        if (mDrawable != null && mDrawable instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mDrawable;
            animationDrawable.start();
        }
    }

    private void stopAnim() {
        mDrawable = mWaitAnim.getDrawable();
        if (mDrawable != null && mDrawable instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mDrawable;
            animationDrawable.stop();
        }
        mAnimAll.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.activity_find_classify_goBack_img:
                finish();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        BookMessageList.MessageList list = chapters.get(position);
        list.setChick(true);
        myIndex.add(position);
        for (int i = 0; i < myIndex.size() - 1; i++) {
            chapters.get(myIndex.get(i)).setHere(false);
        }
        chapters.get(myIndex.get(myIndex.size() - 1)).setHere(true);
        mAdapter.notifyDataSetChanged();
        String link = list.getLink();
        initFromNet();
        getDataBook(link);
    }

    private void initFromNet() {
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl("http://chapter2.zhuishushenqi.com");
        builder.addConverterFactory(ScalarsConverterFactory.create());
        builder.addConverterFactory(GsonConverterFactory.create());
        builder.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.newThread()));
        Retrofit build = builder.build();
        mGetFindClassifyServiceSecond = build.create(GetFindClassifyService.class);
    }

    private void getDataBook(final String link) {
        mProgressDialog = new ProgressDialog(BookMyActivity.this);
        mProgressDialog.setMessage("加载中...");
        mProgressDialog.setCancelable(false);
        mProgressDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Observable<BookMessage> message = mGetFindClassifyServiceSecond.getBookMessage(link);
                message.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<BookMessage>() {
                            @Override
                            public void onCompleted() {
                                String content = mBookChapters.getCpContent();
                                File file = new File(FileCache.mFileCache, mBookChapters.getTitle() + ".txt");
                                if (!file.exists()) {
                                    try {
                                        if (file.createNewFile()) {
                                            FileOutputStream stream = new FileOutputStream(file);
                                            stream.write(content.getBytes("GBK"));
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                                mProgressDialog.dismiss();
                                Intent intent = new Intent(BookMyActivity.this, BookActivity.class);
                                intent.putExtra("MyUrl", file.getAbsolutePath());
                                startActivity(intent);
                            }

                            @Override
                            public void onError(Throwable e) {
                                Toast.makeText(BookMyActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(BookMessage message) {
                                mBookChapters = message.getBookChapters();
                            }
                        });
            }
        });
        mProgressDialog.show();
    }
}
